package com.cheifsteam.springframework.beans.factory.support;

import com.cheifsteam.springframework.beans.BeansException;
import com.cheifsteam.springframework.beans.factory.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 屈燃希
 * @date 2025/2/16 21:30
 * @content
 */
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {


    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>();

    protected Object getCachedObjectForFactoryBean(String beanName)
    {
        Object object = factoryBeanObjectCache.get(beanName);
        return object != NULL_OBJECT ? object : null;
    }

    protected Object getObjectFromFactoryBean(FactoryBean factoryBean, String beanName)  {
        if(factoryBean.isSingleton())
        {
            Object object = getCachedObjectForFactoryBean(beanName);
            if (object == null){
                object = doGetObjectFromFactoryBean(factoryBean, beanName);
                factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
            }
            return (object != NULL_OBJECT ? object : null);
        }else {
            return doGetObjectFromFactoryBean(factoryBean, beanName);
        }
    }

    protected Object doGetObjectFromFactoryBean(FactoryBean factoryBean, String beanName)  {
        try {
            return factoryBean.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", e);
        }
    }
}
